package com.zy.xuanwo.acitivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zy.xuanwo.R;
import com.zy.xuanwo.utils.RegexUtils;
import com.zy.xuanwo.utils.ToastUtils;
import com.zy.xuanwo.utils.URLConstants;
import com.zy.xuanwo.utils.UserInfoSPManager;
import com.zy.xuanwo.view.CleanEditText;
import com.zy.xuanwo.view.CustomToast;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by njb on 2016/7/4.
 */
public class ForgetPassWordActivity extends AppCompatActivity implements View.OnClickListener {


    @Bind(R.id.username_et)
    CleanEditText usernameEt;
    @Bind(R.id.verification_code_et)
    CleanEditText verificationCodeEt;
    @Bind(R.id.verification_code_btn)
    TextView verificationCodeBtn;
    @Bind(R.id.edit_new_password)
    CleanEditText editNewPassword;
    @Bind(R.id.edit_sure_new_password)
    CleanEditText editSureNewPassword;
    @Bind(R.id.btn_sure)
    Button btnSure;

    public static final int RESET_PASSWORD_SUCCESS = 0x33;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x124) {
                int i = (int) msg.obj;
                verificationCodeBtn.setText(i + "s");
                if (i == 1 && !ForgetPassWordActivity.this.isFinishing()) {
                    verificationCodeBtn.setClickable(true);
                    verificationCodeBtn.setText("重新发送");
                    verificationCodeBtn.setBackgroundColor(getResources().getColor(R.color.white));
                }
            }

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activty_forgetpwd);
        ButterKnife.bind(this);
    }

    private void doVerificationCodeRequest() {
        String userName = usernameEt.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            ToastUtils.showShort("手机号或邮箱不能为空");
            return;
        }
        verificationCodeBtn.setClickable(false);
        verificationCodeBtn.setBackgroundColor(getResources().getColor(R.color._D8D8D8));
        countDown();
        if (RegexUtils.checkEmail(userName)) {
            getVerificationCode(URLConstants.EMAIL_VERIFICATION_CODE_URL, userName);
        } else if (RegexUtils.checkMobile(userName)) {
            getVerificationCode(URLConstants.SMS_VERIFICATION_CODE_URL, userName);
        }
    }

    private void getVerificationCode(final String url, String userName) {
        OkHttpUtils.post()
                .url(url)
                .addParams("username", userName)
                .addHeader("token", "446f8fd7-8fc3-426d-8c70-283c021dd380")
                .addHeader("X-Request-Sign", "f033abaf9eac94ffc03d25ee6be445e3, 1467598209")
                .addHeader("X-Application-Id", "3d632345-abd5-4c7c-b157-6d12cd3f0dde")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("response", e + "");
                        ToastUtils.showShort("发送失败");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("response", response + "");
                        if (URLConstants.EMAIL_VERIFICATION_CODE_URL.equals(url)) {
                            ToastUtils.showShort("验证码已发送至邮箱，请查收");
                        } else if (URLConstants.SMS_VERIFICATION_CODE_URL.equals(url)) {
                            ToastUtils.showShort("验证码已发送至手机,请您注意查收短信!");
                        }
                    }
                });
    }

    @OnClick({R.id.left_sliding_menu_iv, R.id.verification_code_btn, R.id.btn_sure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_sure:
                forgetPwd();
                break;
            case R.id.verification_code_btn:
                doVerificationCodeRequest();
                break;
            case R.id.left_sliding_menu_iv:
                startActivity(new Intent(ForgetPassWordActivity.this, LoginActivity.class));
                this.finish();
                break;
        }
    }

    private void forgetPwd() {
        String userName = usernameEt.getText().toString().trim();
        String verificationCode = verificationCodeEt.getText().toString().trim();
        String newPassword = editNewPassword.getText().toString().trim();
        String sureNewPassword = editSureNewPassword.getText().toString().trim();
        if (checkInput(userName, verificationCode,newPassword, sureNewPassword)) {
            Map<String, String> params = new ArrayMap<>();
            params.put("token", "446f8fd7-8fc3-426d-8c70-283c021dd380");
            params.put("X-Request-Sign", "f033abaf9eac94ffc03d25ee6be445e3, 1467598209");
            params.put("X-Application-Id", "3d632345-abd5-4c7c-b157-6d12cd3f0dde");
            OkHttpUtils.post()
                    .url(URLConstants.RESET_PASSWORD_URL)
                    .headers(params)
                    .addParams("username", userName)
                    .addParams("password", newPassword)
                    .addParams("verification_code", verificationCode)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e("excep", e + "");
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Log.e("response", response + "");
                            ToastUtils.showShort("密码重置成功");
                            Intent intent = new Intent(ForgetPassWordActivity.this, LoginActivity.class);
                            intent.putExtra("userName", UserInfoSPManager.getUserName());
                            intent.setFlags(RESET_PASSWORD_SUCCESS);
                            UserInfoSPManager.removeUserInfo();
                            startActivity(intent);
                        }
                    });
        }
    }

    private boolean checkInput(String userName, String verificationCode, String newPassword, String sureNewPassword) {
        if (TextUtils.isEmpty(userName)) {
            ToastUtils.showShort("手机号或邮箱不能为空");
        } else if (TextUtils.isEmpty(verificationCode)) {
            ToastUtils.showShort("验证码不能为空");
        } else if (TextUtils.isEmpty(newPassword)) {
            ToastUtils.showShort("密码不能为空");
        } else if (TextUtils.isEmpty(sureNewPassword)) {
            ToastUtils.showShort("确认密码不能为空");
        } else {
            if (!(RegexUtils.checkMobile(userName) || RegexUtils.checkEmail(userName))) {
                ToastUtils.showShort("手机号或邮箱格式不正确");
            } else if (!newPassword.equals(sureNewPassword)) {
                ToastUtils.showShort("两次输入的密码不一致");
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 倒计时
     */
    private void countDown() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                for (int i = 60; i >= 1; i--) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message message = handler.obtainMessage();
                    message.what = 0x124;
                    message.obj = i;
                    handler.sendMessage(message);
                }
            }
        }.start();
    }
}
